package logic

import (
	"common"
	"common/zapx"
	"errors"
	"gateway/internal/pb"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"time"
)

// VerifySmsCode 验证验证码是否正确
func VerifySmsCode(email, code, event string) bool {
	conn, err := grpc.Dial(
		common.ConsulSerUrl("email"),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
	)
	if err != nil {
		zapx.Logger.Error("链接邮件服务失败", zap.Error(err))
		return false
	}
	defer conn.Close()
	client := pb.NewEmailClient(conn)
	ctx, cancel := common.WithTimeoutContext(time.Second * 2)
	defer cancel()
	_, err = client.VerifyCode(ctx, &pb.VerifyCodeRequest{
		Email: email,
		Event: event,
		Code:  code,
	})
	if err != nil {
		zapx.Logger.Error("验证验证码失败", zap.Error(err))
		return false
	}
	return true
}

// CheckEmailVerifyCode 检查验证码是否有效
func CheckEmailVerifyCode(email, code, event string) error {
	conn, err := grpc.Dial(
		common.ConsulSerUrl("email"),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
	)
	if err != nil {
		zapx.Logger.Error("拨号[email]服务失败", zap.Error(err))
		return errors.New("系统错误")
	}
	defer conn.Close()
	emailClient := pb.NewEmailClient(conn)
	ctx, cancel := common.WithTimeoutContext(time.Second * 5)
	defer cancel()
	_, err = emailClient.CheckCode(ctx, &pb.CheckCodeRequest{
		Email: email,
		Event: event,
		Code:  code,
	})
	if err != nil {
		return err
	}
	return nil
}

// UseVerifyCode 使用验证码
func UseVerifyCode(email, code, event string) error {
	conn, err := grpc.Dial(
		common.ConsulSerUrl("email"),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
	)
	if err != nil {
		zapx.Logger.Error("拨号[email]服务失败", zap.Error(err))
		return errors.New("系统错误")
	}
	defer conn.Close()
	emailClient := pb.NewEmailClient(conn)
	ctx, cancel := common.WithTimeoutContext(time.Second * 5)
	defer cancel()
	_, err = emailClient.UseCode(ctx, &pb.UseCodeRequest{
		Email: email,
		Event: event,
		Code:  code,
	})
	return err
}
